1328B - K-th Beautiful String - CodeForces Solution


binary search brute force combinatorics implementation math *1300

Please click on ads to support us..

Python Code:

t = int(input())
 
def bin_search(low, high, target):
    
    while low < high:
        mid = low + (high - low)//2
        if (mid * (mid + 1))//2 > target:
            high = mid
        else:
            low = mid+1
            res = mid
        
    return low
 
while t > 0:
    
    maxi = int(2e9+7)
    n, k = [int(i) for i in input().split(" ")]
    r = bin_search(0, maxi, k)
    r -= 1
        return_sum = (r * (r+1))//2
    if return_sum == k:
        first_shift = n-1-r
    else:
        first_shift = n-2-r
        
    if return_sum == k:
        second_shift = first_shift+1
    else:
        second_shift = n-1-(k-return_sum-1)
    
        ans = ['a'] * n
    ans[first_shift] = 'b'
    ans[second_shift] = 'b'
    print("".join(ans))
    t -= 1

C++ Code:

#include<bits/stdc++.h>
#define io ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define db double
#define endl "\n"
#define ll long long
#define pii pair<int,int>
using namespace std;
const int N =1e5+10;

void solve(){
    ll n,k;
    cin>>n>>k;
    //1 2 3 4 5 6
    ll l=0,r=n+1;
    while(l+1!=r){
        ll mid=l+r>>1;
        if((mid+1)*mid/2>=k) r=mid;
        else l=mid;
    }
    int pos1=n-r;//1-n-1 2-n-2 5-n-5
    int pos2=k-(ll)r*(r-1)/2;//1-n 2-n-1
    pos2=n+1-pos2;
    string s(n,'a');
    s[pos1-1]='b';
    s[pos2-1]='b';
    cout<<s<<endl;
    
    
}
int main()
{
    io;
    int t;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
    
}


Comments

Submit
0 Comments
More Questions

1408B - Arrays Sum
1430A - Number of Apartments
1475A - Odd Divisor
1454B - Unique Bid Auction
978C - Letters
501B - Misha and Changing Handles
1496A - Split it
1666L - Labyrinth
1294B - Collecting Packages
1642B - Power Walking
1424M - Ancient Language
600C - Make Palindrome
1669D - Colorful Stamp
1669B - Triple
1669A - Division
1669H - Maximal AND
1669E - 2-Letter Strings
483A - Counterexample
3C - Tic-tac-toe
1669F - Eating Candies
1323B - Count Subrectangles
991C - Candies
1463A - Dungeon
1671D - Insert a Progression
1671A - String Building
1671B - Consecutive Points Segment
1671C - Dolce Vita
1669G - Fall Down
4D - Mysterious Present
1316B - String Modification